<template>
    <div class="ipo-card">
        <div class="card-header">
            <h3>新股上市日历</h3>
        </div>
        <div class="card-body">
            <el-table :data="ipoData" style="width: 100%" :show-header="true"
                :header-cell-style="tableConfig.headerCellStyle" :cell-style="tableConfig.cellStyle" size="small" border
                :height="'auto'">
                <el-table-column prop="securityName" label="证券简称"></el-table-column>
                <el-table-column prop="listingDate" label="上市日期" align="right">
                    <template #default="scope">
                        <span>{{ formatDate(scope.row.listingDate) }}</span>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页指示器 -->
            <div class="pagination-indicator" v-if="totalElements > pageSize">
                <span v-for="index in totalPages" :key="index"
                    :class="{ active: currentPage === index, clickable: true }" class="dot"
                    @click="goToPage(index)"></span>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, inject } from 'vue';
import { tableStyle as tableConfig } from '../utils/tableConfig.js';
import { getNewIpos } from '../api/api.js';

// 注入来自Dashboard的暂停更新控制状态

const currentPage = ref(1);
const pageSize = ref(5);
const totalElements = ref(0);
const totalPages = ref(2);
const ipoData = ref([]);
let autoSwitchTimer = null;

const shouldPauseUpdates = inject('shouldPauseUpdates', ref(false));

// 添加定期数据刷新功能和计时器变量
let dataRefreshTimer = null;

// 带检查的数据获取函数
const fetchDataWithCheck = () => {
    // 只有在不暂停更新时才获取新数据
    if (!shouldPauseUpdates.value) {
        fetchIpoData(currentPage.value, pageSize.value);
    } else {
        console.log('IPO日历数据更新已暂停');
    }
};

// 格式化日期
const formatDate = dateStr => dateStr || '';

// 获取IPO数据
const fetchIpoData = async (
    page = currentPage.value,
    size = pageSize.value
) => {
    try {
        const response = await getNewIpos({
            page: page,
            size,
        });

        if (response.code === '200' && response.message === 'success') {
            const { data } = response;
            totalElements.value = data.totalElements;
            totalPages.value =
                data.totalPages ||
                Math.ceil(data.totalElements / data.pageSize);

            // 确保页码有效
            if (currentPage.value > totalPages.value && totalPages.value > 0) {
                currentPage.value = totalPages.value;
            } else {
                currentPage.value = data.currentPage || 1;
            }

            pageSize.value = data.pageSize;

            if (Array.isArray(data.content)) {
                // 对数据按日期倒序排序
                const sortedData = [...data.content].sort((a, b) => {
                    const dateA = new Date(a.listingDate);
                    const dateB = new Date(b.listingDate);
                    return dateB - dateA; // 降序排序
                });

                ipoData.value = sortedData;
            } else {
                ipoData.value = [];
            }
        } else {
            console.error('获取新股上市数据失败:', response.message);
        }
    } catch (error) {
        console.error('获取新股上市数据出错:', error);
    }
};

// 修改页面切换处理函数，使其处理用户交互
const goToPage = pageNumber => {
    if (pageNumber >= 1 && pageNumber <= totalPages.value) {
        // 用户手动切换页面时，暂时停止自动翻页
        if (autoSwitchTimer) {
            clearInterval(autoSwitchTimer);
            autoSwitchTimer = null;
        }

        currentPage.value = pageNumber;
        fetchIpoData(pageNumber, pageSize.value);

        // 手动翻页后延迟恢复自动翻页
        setTimeout(() => {
            startAutoSwitch();
        }, 10000); // 用户操作后10秒恢复自动翻页
    }
};

// 下一页函数
const nextPage = () => {
    if (currentPage.value < totalPages.value) {
        currentPage.value++;
    } else {
        currentPage.value = 1; // 循环到第一页
    }
    fetchIpoData(currentPage.value, pageSize.value);
};

// 上一页函数
const prevPage = () => {
    if (currentPage.value > 1) {
        currentPage.value--;
    } else {
        currentPage.value = totalPages.value; // 循环到最后一页
    }
    fetchIpoData(currentPage.value, pageSize.value);
};

// 修改启动自动翻页函数
const startAutoSwitch = () => {
    // 清除可能存在的定时器
    if (autoSwitchTimer) {
        clearInterval(autoSwitchTimer);
        autoSwitchTimer = null;
    }

    // 仅当总数据量大于每页显示量时才启动自动翻页
    if (totalElements.value > pageSize.value) {
        autoSwitchTimer = setInterval(() => {
            // 只有在不暂停更新时才执行翻页
            if (!shouldPauseUpdates.value) {
                nextPage();
            }
        }, 5000); // 每5秒切换一页
    }
};
// 添加响应式页面大小设置函数
const adjustPageSizeByScreenHeight = () => {
    const height = window.innerHeight;
    const oldSize = pageSize.value; // 保存旧值用于比较

    // 更精细的屏幕高度识别
    if (height >= 1800) {
        pageSize.value = 15; // 超高分辨率屏幕(4K)
    } else if (height >= 1300) {
        pageSize.value = 11; // 高分辨率大屏
    } else if (height >= 1000) {
        pageSize.value = 9; // 中等屏幕
    } else if (height >= 768) {
        pageSize.value = 5; // 适合当前786px高度
    } else if (height >= 600) {
        pageSize.value = 4; // 小屏幕
    } else {
        pageSize.value = 3; // 极小屏幕
    }

    // 仅当页面大小确实变化时才重新加载数据
    if (oldSize !== pageSize.value) {
        console.log(
            `页面大小从 ${oldSize} 变为 ${pageSize.value}，重新加载数据`
        );
        currentPage.value = 1; // 重置为第一页
        fetchIpoData(1, pageSize.value); // 修正：使用fetchIpoData而非getIndicesData
    }
};

// 添加防抖函数
const debounce = (fn, delay) => {
    let timer = null;
    return function (...args) {
        if (timer) clearTimeout(timer);
        timer = setTimeout(() => {
            fn.apply(this, args);
        }, delay);
    };
};

// 创建防抖包装的调整函数
const debouncedAdjustPageSize = debounce(adjustPageSizeByScreenHeight, 300);

// 保存事件监听器引用
const resizeListener = ref(null);

// 组件挂载时获取数据并启动自动翻页和定期刷新
onMounted(() => {
    // 首先调整页面大小
    adjustPageSizeByScreenHeight();
    fetchIpoData();
    // 添加窗口大小变化监听
    window.addEventListener('resize', debouncedAdjustPageSize);
    resizeListener.value = debouncedAdjustPageSize;

    // 数据加载后启动自动翻页（延迟启动以确保数据已加载）
    setTimeout(() => {
        startAutoSwitch();
    }, 1000);

    // 设置定期刷新数据（每30秒刷新一次）
    dataRefreshTimer = setInterval(() => {
        fetchDataWithCheck();
    }, 30000);
});

// 组件卸载前清除所有定时器
onBeforeUnmount(() => {
    // 移除窗口大小变化监听
    if (resizeListener.value) {
        window.removeEventListener('resize', resizeListener.value);
    }

    if (autoSwitchTimer) {
        clearInterval(autoSwitchTimer);
        autoSwitchTimer = null;
    }
    if (dataRefreshTimer) {
        clearInterval(dataRefreshTimer);
        dataRefreshTimer = null;
    }
});
</script>

<style scoped>
@import '../assets/css/style.css';

.ipo-card {
    background-color: #001e4a;
    border-radius: 5px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    height: 100%;
}

/* 分页控制样式 - 修改为固定位置 */
.pagination-indicator {
    display: flex;
    justify-content: center;
    padding: 10px 0 5px;
    margin-top: auto;
    /* 确保始终在底部 */
}

.dot {
    width: 8px;
    height: 8px;
    border-radius: 50%;
    background-color: #4a5e8c;
    margin: 0 5px;
}

.dot.active {
    background-color: #8cd6ff;
}

/* 使点可点击 */
.dot.clickable {
    cursor: pointer;
    transition: transform 0.2s, background-color 0.2s;
}

.dot.clickable:hover {
    transform: scale(1.2);
    background-color: #6a9cc0;
}

/* 按钮样式 */
:deep(.el-button--text) {
    color: #8cd6ff;
}

:deep(.el-button--text:hover) {
    color: #ffffff;
}

/* 适应大屏幕 */
@media (min-height: 1200px) {
    .card-header h3 {
        font-size: 22px;
    }

    .card-body {
        padding: 20px;
    }
}

/* 适应4K屏幕 */
@media (min-height: 1800px) {
    .card-header h3 {
        font-size: 26px;
    }

    .card-body {
        padding: 25px;
    }
}
</style>
